<template>
    <div class="container">
        <h1>{{msg}}</h1>
        <div class="card">
            <div class="card-header">Vue Axios Get</div>
            <div class="card-body">
                <div class="input-group input-group-sm">
                    <button class="btn btn-sm btn-primary" @click="getAllData">Get All</button>
                    <input type="text" ref="get_id" class="form-control ml-2" placeholder="Id" />
                    <div class="input-group-append">
                        <button class="btn btn-sm btn-primary" @click="getDataById">Get by Id</button>
                    </div>
                    <input type="text" ref="get_title" class="form-control ml-2" placeholder="Title" />
                    <div class="input-group-append">
                        <button class="btn btn-sm btn-primary" @click="getDataByTitle">Find By Title</button>
                    </div>
                    <button class="btn btn-sm btn-warning ml-2" @click="clearGetOutput">Clear</button>
                </div>
                <div v-if="getResult" class="alert alert-secondary mt-2" role="alert" style="text-align: left"><pre>{{getResult}}</pre></div>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator'
import http from "../http-common";

@Component
export default class AxiosGetJSONData extends Vue {
    @Prop() private msg!: string
    private getResult:any = "";

    $refs!:{
        get_id:HTMLInputElement;
        get_title:HTMLInputElement;
    }

    public formatResponse(res:any):string{
        let jsonData =  JSON.stringify(res,null,4);
        console.log(jsonData);
        return jsonData;
    }

    public clearGetOutput():void{
        this.getResult = "";
    }

    public getAllData():void{
        http.get("/api/tutorials").then(res =>{
            let result = {
                status:res.status + "-" + res.statusText,
                headers:res.headers,
                data:res.data
            }
            this.getResult = this.formatResponse(result);
        })
    }

    public getDataById():void{
        let id = this.$refs.get_id.value;
        http.get("/api/tutorial/" + id).then(res =>{
            let result = {
                status:res.status + "-" + res.statusText,
                headers:res.headers,
                data:res.data
            }
            this.getResult = this.formatResponse(result);
        })
    }

    public getDataByTitle():void{
        let title = this.$refs.get_title.value;
        http.get("/api/tutorials",{
            params:{
                title:title
            }
        }).then(res =>{
            let result = {
                status:res.status + "-" + res.statusText,
                headers:res.headers,
                data:res.data
            }
            this.getResult = this.formatResponse(result);
        })
    }
}
</script>

<style scoped>
</style>
